package test;

import bean.Users;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.ArrayList;

public class Demo {
    public static void main(String[] args) {
        //java->json
        Users users = new Users(11,"aaa","123456",123.45);
        JSONObject jsonObject = JSONObject.fromObject(users);
        System.out.println(jsonObject);

        //json->java
        String str = "{\"money\":123.45,\"password\":\"123456\",\"uid\":11,\"username\":\"aaa\"}";
        JSONObject jsonObject1 = JSONObject.fromObject(str);
        Object o = JSONObject.toBean(jsonObject1, Users.class);
        System.out.println("o="+o);

        //java集合->json
        ArrayList arrayList = new ArrayList();
        arrayList.add(new Users(1,"a","123",111.11));
        arrayList.add(new Users(2,"b","456",222.11));
        arrayList.add(new Users(3,"c","789",333.11));
        JSONArray jsonArray = JSONArray.fromObject(arrayList);
        System.out.println(jsonArray);

        //json->java集合
        String str2 = "[{\"money\":111.11,\"password\":\"123\",\"uid\":1,\"username\":\"a\"},{\"money\":222.11,\"password\":\"456\",\"uid\":2,\"username\":\"b\"},{\"money\":333.11,\"password\":\"789\",\"uid\":3,\"username\":\"c\"}]";
        JSONArray jsonArray2 = JSONArray.fromObject(str2);
        Object[] o1 = (Object[]) JSONArray.toArray(jsonArray2, Users.class);
        for (Object o2 : o1) {
            System.out.println(o2);
        }
    }
}
